package com.newtouch.bxzs.database.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.newtouch.bxzs.common.base.BaseErrorEnum;
import com.newtouch.bxzs.common.base.BaseException;
import com.newtouch.bxzs.common.base.model.DataDictionary;
import com.newtouch.bxzs.common.base.model.DataDictionaryEntry;
import com.newtouch.bxzs.common.base.model.bo.DataDictionaryValueBO;
import com.newtouch.bxzs.common.base.util.EntityToBeanUtils;
import com.newtouch.bxzs.common.base.util.UserDetailUtil;
import com.newtouch.bxzs.database.controller.DataDictionaryController;
import com.newtouch.bxzs.database.mapper.DataDictionaryEntryMapper;
import com.newtouch.bxzs.database.mapper.DataDictionaryMapper;
import com.newtouch.bxzs.database.model.bo.DataDictionaryEntryBO;
import com.newtouch.bxzs.database.model.vo.DataDictionaryEntryChangeVO;
import com.newtouch.bxzs.database.model.vo.DataDictionaryEntryListVO;
import com.newtouch.bxzs.database.model.vo.DataDictionaryEntryVO;
import com.newtouch.bxzs.database.service.DataDictionaryEntryService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 数据字典项管理service接口的实现类
 *
 * <p>
 * <b>History:</b>
 * <table border="1">
 * <tr>
 * <th>Date</th>
 * <th>Operator</th>
 * <th>Memo</th>
 * </tr>
 * <tr>
 * <td>2021/1/5</td>
 * <td>zhangqianyang</td>
 * <td>Create</td>
 * </tr>
 * </table>
 *
 * @author zhangqianyang
 * @version 1.0.0
 * @since 1.0.0
 */

@Service
public class DataDictionaryEntryServiceImpl implements DataDictionaryEntryService {
    @Resource
    private DataDictionaryEntryMapper dataDictionaryEntryMapper;

    @Resource
    private DataDictionaryMapper dataDictionaryMapper;

    /**
     * 静态变量：日志
     */
    private static final Log logger = LogFactory.getLog(DataDictionaryController.class);

    /**
     * (non-Javadoc)
     * <p>
     * <p>
     * com.newtouch.bxzs.message.service.DataDictionaryService#getDataDictionaryList(com.newtouch.bxzs.database.model.vo.DataDictionaryVO)
     */
    @Override
    public IPage<DataDictionaryEntryBO> getDataDictionaryEntryListById(DataDictionaryEntryListVO dataDictionaryEntryListVO) {
        if (dataDictionaryEntryListVO == null || dataDictionaryEntryListVO.getCurrentPage() == null || dataDictionaryEntryListVO.getPageSize() == null) {
            throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
        }
        /* 拿到当前页和每页数量*/
        Page<DataDictionaryEntry> dataDictionaryEntryPage = new Page<>(dataDictionaryEntryListVO.getCurrentPage(), dataDictionaryEntryListVO.getPageSize());
        //实例化QueryWrapper
        QueryWrapper<DataDictionaryEntry> query = new QueryWrapper<>();
        /*根据数据字典id查询*/
        query.eq("DATA_DICTIONARY_ID", dataDictionaryEntryListVO.getDataDictionaryId());
        /*选择排序顺序（更新时间）*/
        query.orderByDesc("UPDATE_TIME");
        /* 通过输入条件查询*/
        IPage<DataDictionaryEntry> iPage = dataDictionaryEntryMapper.selectPage(dataDictionaryEntryPage, query);
        if (iPage == null || CollectionUtil.isEmpty(iPage.getRecords())) {
            return null;
        }
        IPage<DataDictionaryEntryBO> boiPage = new Page<>();
        // 设置iPage*/
        boiPage.setRecords(EntityToBeanUtils.copyBean(iPage.getRecords(), DataDictionaryEntryBO.class));
        boiPage.setTotal(iPage.getTotal());
        boiPage.setSize(iPage.getSize());
        boiPage.setPages(iPage.getPages());
        boiPage.setCurrent(iPage.getCurrent());
        return boiPage;
    }

    /**
     * (non-Javadoc)
     * <p>
     * <p>
     * com.newtouch.bxzs.message.service.DataDictionaryService#deleteDataDictionarieEntry(List <String>)
     */
    @Override
    public String deleteDataDictionaryEntry(List<String> dataDictionaryEntryIds) {
        if (CollectionUtil.isEmpty(dataDictionaryEntryIds)) {
            logger.info("数据字典项id集合输入为空");
            throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
        }
        //实例化QueryWrapper
        QueryWrapper<DataDictionaryEntry> query = new QueryWrapper<>();
        query.in("DATA_DICTIONARY_ENTRY_ID", dataDictionaryEntryIds);
        List<DataDictionaryEntry> list = dataDictionaryEntryMapper.selectList(query);
        String dataDictionaryId = null;
        if(CollectionUtils.isEmpty(list)){
            throw new BaseException(BaseErrorEnum.REQUEST_PARAMETER_ERROR);
        }
        for (DataDictionaryEntry dataDictionaryEntry : list) {
            if (list.size() == 0 || dataDictionaryEntry == null || dataDictionaryEntry.getEnableFlag()) {
                logger.info("数据字典项id集合输入异常");
                throw new BaseException(BaseErrorEnum.ENABLE_USE);
            }
            dataDictionaryId = dataDictionaryEntry.getDataDictionaryId();
        }
        /* 设置修改人状态和修改时间 */
        QueryWrapper<DataDictionaryEntry> updateQuery = new QueryWrapper<>();
        updateQuery.in("DATA_DICTIONARY_ENTRY_ID", dataDictionaryEntryIds);
        DataDictionaryEntry dataDictionaryEntry = new DataDictionaryEntry();
        dataDictionaryEntry.setUpdateTime(new Date());
        dataDictionaryEntry.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
        dataDictionaryEntryMapper.update(dataDictionaryEntry, updateQuery);
        /*批量逻辑删除数据字典项*/
        dataDictionaryEntryMapper.deleteBatchIds(dataDictionaryEntryIds);
        if (StringUtils.isEmpty(dataDictionaryId)) {
            return null;
        }
        return dataDictionaryId;
    }

    /**
     * (non-Javadoc)
     * <p>
     * <p>
     * com.newtouch.bxzs.message.service.DataDictionaryService#modifyDataDictionarieEntry(com.newtouch.bxzs.database.model.vo.DataDictionaryVO)
     */
    @Override
    public String modifyDataDictionaryEntry(DataDictionaryEntryVO dataDictionaryEntryVO) {
        if (dataDictionaryEntryVO == null || StringUtils.isEmpty(dataDictionaryEntryVO.getDataDictionaryEntryName()) ||
                StringUtils.isEmpty(dataDictionaryEntryVO.getDataDictionaryEntryValue()) ||
                StringUtils.isEmpty(dataDictionaryEntryVO.getDataDictionaryId()) ||
                StringUtils.isEmpty(dataDictionaryEntryVO.getDataDictionaryEntryAbbreviation())) {
            logger.info("输入必填项为空");
            throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
        }
        //实例化QueryWrapper
        QueryWrapper<DataDictionaryEntry> query = new QueryWrapper<>();
        /*根据数据字典id查询*/
        query.eq("DATA_DICTIONARY_ID", dataDictionaryEntryVO.getDataDictionaryId());
        List<DataDictionaryEntry> dataDictionaryEntries = dataDictionaryEntryMapper.selectList(query);
        if (!CollectionUtils.isEmpty(dataDictionaryEntries)) {
            for (DataDictionaryEntry dataDictionaryEntry : dataDictionaryEntries) {
                if (dataDictionaryEntry.getDataDictionaryEntryValue().equals(dataDictionaryEntryVO.getDataDictionaryEntryValue())
                        && !dataDictionaryEntry.getDataDictionaryEntryId().equals(dataDictionaryEntryVO.getDataDictionaryEntryId())) {
                    logger.error("数据字典项值不能重复");
                    throw new BaseException(BaseErrorEnum.DATA_EXISTS);
                }
                if (dataDictionaryEntry.getDataDictionaryEntryName().equals(dataDictionaryEntryVO.getDataDictionaryEntryName())
                        && !dataDictionaryEntry.getDataDictionaryEntryId().equals(dataDictionaryEntryVO.getDataDictionaryEntryId())) {
                    logger.error("数据字典项名称不能重复");
                    throw new BaseException(BaseErrorEnum.DATA_EXISTS);
                }
            }
        }
        /* 实例化DataDictionaryEntry*/
        DataDictionaryEntry dataDictionaryEntry = new DataDictionaryEntry();
        /* 使用工具直接进行实体与BO的复制转换，前面是来源，后面是目标*/
        BeanUtil.copyProperties(dataDictionaryEntryVO, dataDictionaryEntry);
        Date date = new Date();
        /*如果dataDictionaryEntryId为空，新增数据字典项 */
        if (StringUtils.isEmpty(dataDictionaryEntry.getDataDictionaryEntryId())) {
            dataDictionaryEntry.setCreateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
            dataDictionaryEntry.setCreateTime(date);
            dataDictionaryEntry.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
            dataDictionaryEntry.setUpdateTime(date);
            dataDictionaryEntry.setEnableFlag(false);
            dataDictionaryEntry.setDeleteFlag(false);
            dataDictionaryEntryMapper.insert(dataDictionaryEntry);
        } else {
            if ((dataDictionaryEntryMapper.selectById(dataDictionaryEntry.getDataDictionaryEntryId())).getEnableFlag()) {
                logger.error("只能修改未启用的数据字典项");
                throw new BaseException(BaseErrorEnum.ENABLE_USE);
            }
            dataDictionaryEntry.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
            dataDictionaryEntry.setUpdateTime(date);
            /*如果dataDictionaryEntryId不为空，修改数据字典项 */
            dataDictionaryEntryMapper.updateById(dataDictionaryEntry);
        }
        return "新增/修改数据字典项成功";
    }

    /**
     * (non-Javadoc)
     * <p>
     * <p>
     * com.newtouch.bxzs.message.service.DataDictionaryService#changeDataDictionarieEntryStatus(java.lang.String,java.lang.Integer)
     */
    @Override
    public String changeDataDictionaryEntryStatus(DataDictionaryEntryChangeVO dataDictionaryEntryChangeVO) {
        /* 判断dataDictionaryEntryId是否为空  || 判断enableFlag是否为空 */
        if (dataDictionaryEntryChangeVO == null || StringUtils.isEmpty(dataDictionaryEntryChangeVO.getDataDictionaryEntryId()) || StringUtils.isEmpty(dataDictionaryEntryChangeVO.getEnableFlag())) {
            logger.info("修改状态输入异常");
            throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
        }
        /* 实例化QueryWrapper */
        QueryWrapper<DataDictionaryEntry> query = new QueryWrapper<>();
        /* 实例化DataDictionaryEntry */
        DataDictionaryEntry dataDictionaryEntry = new DataDictionaryEntry();
        /* 设置dataDictionaryEntryId为sql条件*/
        query.eq("DATA_DICTIONARY_ENTRY_ID", dataDictionaryEntryChangeVO.getDataDictionaryEntryId());
        /* 设置状态，修改人，和修改时间*/
        dataDictionaryEntry.setEnableFlag(dataDictionaryEntryChangeVO.getEnableFlag());
        dataDictionaryEntry.setUpdateUserId(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
        dataDictionaryEntry.setUpdateTime(new Date());
        /* 修改启用禁用状态*/
        dataDictionaryEntryMapper.update(dataDictionaryEntry, query);
        return dataDictionaryEntryMapper.selectById(dataDictionaryEntryChangeVO.getDataDictionaryEntryId()).getDataDictionaryId();
    }

    /**
     * (non-Javadoc)
     * <p>
     * <p>
     * com.newtouch.bxzs.message.service.DataDictionaryService#getDataDictionaryEntryListByCode(java.lang.String,java.lang.String)
     */
    @Override
    public List<DataDictionaryValueBO> getDataDictionaryEntryListByCode(String dictionaryCode, String dataDictionaryEntryName) {
        if(StringUtils.isEmpty(dictionaryCode)){
            throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
        }
        QueryWrapper<DataDictionary> dataQuery = new QueryWrapper<>();
        dataQuery.eq("DATA_DICTIONARY_CODE",dictionaryCode);
        DataDictionary dataDictionary = dataDictionaryMapper.selectOne(dataQuery);
        if(BeanUtil.isEmpty(dataDictionary)){
            throw new BaseException(BaseErrorEnum.REQUEST_PARAMETER_ERROR);
        }
        QueryWrapper<DataDictionaryEntry> query = new QueryWrapper<>();
        query.eq("DATA_DICTIONARY_ID",dataDictionary.getDataDictionaryId());
        if(!StringUtils.isEmpty(dataDictionaryEntryName)){
            query.like("DATA_DICTIONARY_ENTRY_NAME",dataDictionaryEntryName);
        }
        List<DataDictionaryEntry> dataDictionaryEntries = dataDictionaryEntryMapper.selectList(query);
        if(CollectionUtils.isEmpty(dataDictionaryEntries)){
            return null;
        }
        return EntityToBeanUtils.copyBean(dataDictionaryEntries,DataDictionaryValueBO.class);
    }

    /**
     * (non-Javadoc)
     * <p>
     * <p>
     * com.newtouch.bxzs.message.service.DataDictionaryService#getDataDictionarieEntryDetail(java.lang.String,java.lang.String)
     */
    @Override
    public DataDictionaryEntryBO getDataDictionaryEntryDetail(String dataDictionaryEntryId) {
        if (StringUtils.isEmpty(dataDictionaryEntryId)) {
            logger.info("数据字典项id输入为空");
            throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
        }
        /*通过id查询数据字典项*/
        DataDictionaryEntry dataDictionaryEntry = dataDictionaryEntryMapper.selectById(dataDictionaryEntryId);
        if (BeanUtil.isEmpty(dataDictionaryEntry)) {
            logger.info("数据字典项id输入错误");
            return null;
        }
        /*实例化DataDictionaryEntryBO*/
        DataDictionaryEntryBO dataDictionaryEntryBO = new DataDictionaryEntryBO();
        /* 使用工具直接进行实体与BO的复制转换，前面是来源，后面是目标*/
        BeanUtil.copyProperties(dataDictionaryEntry, dataDictionaryEntryBO);
        return dataDictionaryEntryBO;
    }
}
